
package org.openeai.lite.console.actionhandlers;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.apache.log4j.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.openeai.lite.common.control.RouterController;
import org.openeai.lite.common.util.Constants;
import org.openeai.lite.common.util.FileUtils;


@ManagedBean(name = "routerCustomConfigActionHandler")
@RequestScoped
public class RouterCustomConfigActionHandler
{

    private static Logger log = Logger.getLogger(RouterCustomConfigActionHandler.class);


    private UploadedFile uploadedConfigFile;

    private String tempConfigFile;

    private String message;

    public UploadedFile getUploadedConfigFile()
    {
        return this.uploadedConfigFile;
    }

    public void setUploadedConfigFile(UploadedFile uploadedConfigFile)
    {
        this.uploadedConfigFile = uploadedConfigFile;
    }

    public String getMessage()
    {
        return this.message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    public void uploadConfigFileAndStart() throws Exception
    {
        try
        {
            if (this.uploadedConfigFile != null)
            {
                this.tempConfigFile = uploadedConfigFile.getName();
                log.info("Processing file " + tempConfigFile);
                
                new FileUtils().copyToUploadedCustomConfig(uploadedConfigFile);
                
                RouterController.getInstance().start(Constants.STARTUP_CUSTOM, Constants.CUSTOM_CONFIG_FILENAME);
                setMessage("Message router started with configuration file " + tempConfigFile);
            }
            else
            {
                setMessage("Cannot load custom configuration file " + tempConfigFile);
                log.error("Cannot load custom configuration file " + tempConfigFile);
            }
        }
        catch (Exception e)
        {
            setMessage(e.getMessage());
            log.error(e);
        }
    }

}
